/**
 * Filename: MemberActivity.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/3/6 14:45
 */
package com.github.postsanf.yinian.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.OvershootInterpolator;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.BaseApplication;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.AlbumMemberAdapter;
import com.github.postsanf.yinian.bean.YNAlbum;
import com.github.postsanf.yinian.bean.YNMember;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.YNSingleton;
import com.github.postsanf.yinian.entity.YNAlbumMemberResponse;
import com.github.postsanf.yinian.service.RemoveMemberService;
import com.github.postsanf.yinian.utils.DisplayUtils;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.SpUtils;
import com.github.postsanf.yinian.utils.WrapContentLinearLayoutManager;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import jp.wasabeef.recyclerview.animators.SlideInRightAnimator;

public class MemberActivity extends BaseActivity implements View.OnClickListener {
    private RecyclerView rv_members;
    private AlbumMemberAdapter mAdapter;
    private List<YNMember> mMemberDatas = new ArrayList<>();
    private RelativeLayout rl_lead;
    private boolean memberLead = false;
    private ImageView iv_back;
    private ImageView iv_select;
    private RelativeLayout rl_invite;
    private RelativeLayout rl_remove;
    private boolean show = false;
    private RelativeLayout rl_select;
    private boolean select = false;
    private RelativeLayout rl_complete;
    private ImageView iv_complete;
    private String removeID = null;
    private String removeName = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yn_activity_member);
        registerBroadcastReceiver();
        initView();
    }

    private void initView() {
        rv_members = (RecyclerView) findViewById(R.id.rv_members);
        iv_back = ((ImageView) findViewById(R.id.iv_back));
        iv_select = ((ImageView) findViewById(R.id.iv_select));
        rl_invite = ((RelativeLayout) findViewById(R.id.rl_invite));
        rl_remove = ((RelativeLayout) findViewById(R.id.rl_remove));
        rl_select = ((RelativeLayout) findViewById(R.id.rl_select));
        rl_complete = ((RelativeLayout) findViewById(R.id.rl_complete));
        iv_complete = ((ImageView) findViewById(R.id.iv_complete));
        rl_lead = ((RelativeLayout) findViewById(R.id.rl_lead));
        iv_complete.setOnClickListener(this);
        rl_select.setOnClickListener(this);
        rl_invite.setOnClickListener(this);
        rl_remove.setOnClickListener(this);
        iv_back.setOnClickListener(this);
        iv_select.setOnClickListener(this);
        rl_lead.setOnClickListener(this);
        rv_members.setLayoutManager(new WrapContentLinearLayoutManager(this));
//        rv_members.setItemAnimator(new SlideInRightAnimator(new OvershootInterpolator(1f)));
//        rv_members.getItemAnimator().setAddDuration(300);
//        rv_members.getItemAnimator().setRemoveDuration(300);
//        rv_members.getItemAnimator().setMoveDuration(300);
//        rv_members.getItemAnimator().setChangeDuration(300);
        mAdapter = new AlbumMemberAdapter(this, mMemberDatas, YNSingleton.getInstance().getCurAlbum(), false, application.getCurID() + "");
        rv_members.setAdapter(mAdapter);
        rv_members.setHasFixedSize(true);
        memberLead = SpUtils.getBoolean(MemberActivity.this, "MemberLead");
        if (!memberLead) {
            rl_lead.setVisibility(View.VISIBLE);
        } else {
            rl_lead.setVisibility(View.GONE);
        }
        noticeServiceInit();
    }

    // 更新成员数据
    private void updateView(List<YNMember> memberList) {
        mMemberDatas.addAll(memberList);
        mAdapter.notifyDataSetChanged();
    }

    BroadcastReceiver mMemberBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case ACTIONs.remove:
                    noticeServiceInit();
                    break;
                case ACTIONs.IsSelected:
                    if (mAdapter.uid.size() > 0) {
                        iv_complete.setImageResource(R.drawable.do_complete);
                    } else {
                        iv_complete.setImageResource(R.drawable.do_complete_press);
                    }
                    break;
            }
        }
    };

    private void registerBroadcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.remove);
        myIntentFilter.addAction(ACTIONs.IsSelected);
        registerReceiver(mMemberBroadcastReceiver, myIntentFilter);
    }

    // 通知后台加载数据
    private void noticeServiceInit() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_GROUP_ID, String.valueOf(application.getCurGid()));
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynShowMember))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNAlbumMemberResponse resAlbumMember = gson.fromJson(s, YNAlbumMemberResponse.class);
                        if (resAlbumMember != null && ReqUtils.isSuccess(resAlbumMember.getCode())) {
                            mMemberDatas.clear();
                            updateView(resAlbumMember.getData());
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        BaseApplication.getInstance().mActivitys.remove(this);
        unregisterReceiver(mMemberBroadcastReceiver);
    }

    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                if (select) {
                    select = false;
                    mAdapter.updateData(false);
                    mAdapter.uid.clear();
                    mAdapter.notifyDataSetChanged();
                    iv_select.setVisibility(View.VISIBLE);
                    rl_complete.setVisibility(View.GONE);
                } else {
                    finish();
                }
                break;
            case R.id.iv_select:
                show = !show;
                if (show) {
                    rl_select.setVisibility(View.VISIBLE);
                } else {
                    rl_select.setVisibility(View.GONE);
                }
                break;
            case R.id.rl_invite:
                YNAlbum listItems = YNSingleton.getInstance().getCurAlbum();
                Intent intent = new Intent(MemberActivity.this, InviteChooseActivity.class);
                intent.putExtra(CommonConstants.YNDATAS, listItems);
                startActivity(intent);
                Intent statintentinvite = new Intent(ACTIONs.record);
                statintentinvite.putExtra("key", "成员列表·邀请好友_4");
                statintentinvite.putExtra("value", 1);
                sendBroadcast(statintentinvite);
                show = !show;
                rl_select.setVisibility(View.GONE);
                break;
            case R.id.rl_remove:
                //空间创建者才能移除成员
                if (YNSingleton.getInstance().getCurAlbum().getGcreator().equals(application.getCurID() + "")) {
                    mAdapter.updateData(true);
                    mAdapter.notifyDataSetChanged();
                    select = true;
                    iv_select.setVisibility(View.GONE);
                    rl_complete.setVisibility(View.VISIBLE);
                } else {
                    android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);
                    builder.setCancelable(false);
                    final android.support.v7.app.AlertDialog dlg = builder.create();
                    dlg.show();
                    Window window = dlg.getWindow();
                    window.setContentView(R.layout.pub_tip_dialog);
                    window.setBackgroundDrawableResource(R.color.transparent);
                    WindowManager.LayoutParams layout = dlg.getWindow().getAttributes();
                    layout.width = DisplayUtils.getScreenWidthPixels(this) - DisplayUtils.dp2px(this, 35 * 2);
                    dlg.getWindow().setAttributes(layout);
                    TextView tt = (TextView) window.findViewById(R.id.pp_title);
                    tt.setText("提示");
                    TextView content = (TextView) window.findViewById(R.id.pp_content);
                    content.setText("对不起，只有圈子的创建者才能移除成员！");
                    final TextView ok = (TextView) window.findViewById(R.id.btn_ok);
                    ok.setText("确定");
                    ok.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            dlg.cancel();
                        }
                    });
                }
                show = !show;
                rl_select.setVisibility(View.GONE);
                break;
            case R.id.rl_select:
                show = !show;
                rl_select.setVisibility(View.GONE);
                break;
            case R.id.iv_complete:
                if (mAdapter.uid.size() == 0) {
                    return;
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(MemberActivity.this);
                builder.setMessage("确定要移除所选成员吗？");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intentRemove = new Intent(MemberActivity.this, RemoveMemberService.class);
                        for (int i = 0; i < mAdapter.uid.size(); i++) {
                            if (removeID == null) {
                                removeID = mAdapter.uid.get(i);
                                removeName = mAdapter.nickName.get(i);
                            } else {
                                removeID = removeID + "," + mAdapter.uid.get(i);
                                removeName = removeName + "," + mAdapter.nickName.get(i);
                            }
                        }
                        intentRemove.putExtra("userid", removeID);
                        intentRemove.putExtra("groupid", application.getCurGid() + "");
                        intentRemove.putExtra("owner", YNSingleton.getInstance().getCurAlbum().getGcreator());
                        intentRemove.putExtra("nickName", removeName);
                        startService(intentRemove);
                        iv_complete.setImageResource(R.drawable.do_complete_press);
                        dialog.dismiss();
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mAdapter.updateData(true);
                        mAdapter.uid.clear();
                        mAdapter.notifyDataSetChanged();
                        iv_complete.setImageResource(R.drawable.do_complete_press);
                        dialog.dismiss();
                    }
                });
                builder.create().show();
                break;
            case R.id.rl_lead:
                rl_lead.setVisibility(View.GONE);
                SpUtils.put(MemberActivity.this, "MemberLead", true);
                break;
        }
    }
}